package student.duing.wangli;

/**
 * 最大子序和
 */
public class MaxSubArray {
    public static void main(String[] args) {
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
//        int[] nums = new int[]{-2,-3,-1,2,1,-7};
        System.out.println(maxSubArray(nums));
    }

    public static int maxSubArray(int[] nums) {
        //边界值的判断
        if (nums.length == 1) return nums[0];
        //记录最大值
        int max = Integer.MIN_VALUE;

        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        max = dp[0];

        for (int i = 1; i < dp.length; i++) {
            if(dp[i - 1] > 0) {
                dp[i] = dp[i - 1] + nums[i];
            }else{
                dp[i] = nums[i];
            }
            //所求的值 比max还大
            if(dp[i] > max){
                //更新max
                max = dp[i];
            }

        }
        return max;
    }


}
